package com.crazymo.messenger.rawmessenger;


import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;

public class MessengerService extends Service {
    public final static String TAG = "MessengerIPC";
    public final static String KEY_NAME = "Name";
    public final static String KEY_RESP = "Response";
    public final static int MSG_WHAT_HELLO = 100;
    public final static int MSG_WHAT_RESP = 1001;
    /**
     * 一个用于跨进程的序列化对象，包裹着IMessenger AIDL接口
     */
    private static final Messenger messenger = new Messenger(new MessengerServerHandler());

    private static class MessengerServerHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            doHandleMessage(msg);
        }
    }

    /**
     * 处理其他进程发过来的消息
     * @param msg
     */
    private static void doHandleMessage(Message msg) {
        if (msg != null) {
            String ret = "hello ";
            //接收客户端的消息并处理
            if (msg.what == MSG_WHAT_HELLO) {
                Log.e(TAG, "receive msg from client=" + msg.getData().getString(KEY_NAME));
                try {
                    Thread.sleep(1_000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                ret += msg.getData().getString(KEY_NAME);
                //把处理结果封装到Message返回给客户端
                Message reply = Message.obtain(null, MSG_WHAT_RESP);
                Bundle bundle = new Bundle();
                bundle.putString(KEY_RESP, ret);
                reply.setData(bundle);
                try {
                    //msg.replyTo @ android.os.Messenger类型，Messager.replyTo指向的客户端的Messenger,而Messenger又持有客户端的一个Binder对象（MessengerImpl）。服务端正是利用这个Binder对象做的与客户端的通信。
                    if (msg.replyTo != null) {
                        msg.replyTo.send(reply);
                    }
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        } else {
            Log.e(TAG, "handle client empty msg");
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        //返回Messenger的IBinder对象，当bindService 执行时候就会触发该回调，就可以拿到服务端的IBinder对象
        return messenger.getBinder();
    }
}
